<template>
    <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="ruleFormRef">
        <el-form-item label="用户名：" prop="user">
            <el-input v-model="formInline.user" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="部门" prop="region">
            <el-select v-model="formInline.region" placeholder="请选择部门">
                <el-option v-for="item in state.deptData" :key="item.key" :label="item.text"
                    :value="Number(item.value)">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item prop="date">
            <div class="block">
                <span class="demonstration">创建时间：</span>
                <el-date-picker v-model="formInline.date" type="daterange" range-separator="～" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
    <div class="botton-group">
        <el-button type="primary" plain @click="addUser()">新增</el-button>
        <el-button plain @click="delect()">删除</el-button>
        <el-button plain @click="toggleSelection()">清空所选</el-button>
        <el-dropdown trigger="click">
            <span class="el-dropdown-link">
                <el-button plain @click="">更多操作</el-button>
            </span>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item @click="dataExcel">导出 Excel</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
    <el-table class="table" ref="multipleTableRef" :data="state.userData" width="100%" height="420"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" sortable width="180" />
        <el-table-column property="ssex" label="性别" width="120">
            <template #default="scope">{{scope.row.ssex==0?'男':(scope.row.ssex==1?'女':'保密')}}</template>
        </el-table-column>
        <el-table-column property="email" label="邮箱" show-overflow-tooltip>
            <template #default="scope">{{scope.row.email==null?'未填写': scope.row.email}}</template>
        </el-table-column>
        <el-table-column property="deptName" label="部门" show-overflow-tooltip>
            <template #default="scope">{{scope.row.deptName==null?'未填写': scope.row.deptName}}</template>
        </el-table-column>
        <el-table-column property="mobile" label="电话" show-overflow-tooltip>
            <template #default="scope">{{scope.row.mobile==null?'未填写': scope.row.mobile}}</template>
        </el-table-column>
        <el-table-column prop="tag" label="状态" width="100" :filters="[
          { text: '正常', value: '1' },
          { text: '锁定', value: '0' },
        ]" :filter-method="filterTag" filter-placement="bottom-end">
            <template #default="scope">
                <el-tag :type="scope.row.status === '1' ? 'success' : 'error'" disable-transitions>
                    {{scope.row.status==1?'正常':'锁定'}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column property="createTime" label="创建时间" show-overflow-tooltip />
        <el-table-column property="" label="操作" show-overflow-tooltip>
            <template #default="scope">
                <el-button :icon="Edit" circle @click="handleEdit(scope.$index, scope.row)" />
                <el-button :icon="View" circle @click="handleDelete(scope.$index, scope.row)" />
            </template>
        </el-table-column>>
    </el-table>
    <div class="demo-pagination-block">
        <el-pagination v-model:currentPage="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 20, 30, 40]"
            :small="small" :disabled="disabled" :background="background" :total="state.page"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>

    <el-dialog v-model="dialogFormVisible" :title="state.forChange">
        <el-form :model="form" ref="ruleFormRef">
            <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                <el-input v-model="form.data.username" autocomplete="off" />
            </el-form-item>
            <el-form-item type="password" label="密码" prop="password" :label-width="formLabelWidth">
                <el-input type="password" :disabled="state.active" v-model="form.data.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
                <el-input v-model="form.data.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
                <el-input v-model="form.data.mobile" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色" prop="role" :label-width="formLabelWidth">
                <el-select v-model="form.data.role" multiple placeholder="请选择角色" style="width: 100%">
                    <el-option v-for="item in state.roleData" :key="item.roleId" :label="item.roleName"
                        :value="String(item.roleId)" />
                </el-select>
            </el-form-item>

            <el-form-item label="部门" prop="dept" :label-width="formLabelWidth">
                <el-select v-model="form.data.dept" placeholder="请选择部门">
                    <el-option v-for="item in state.deptData" :key="item.key" :label="item.text" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态" style="margin-left: 100px;" prop="status">
                <el-radio-group v-model="form.data.status">
                    <el-radio label="1" value="1">
                        有效
                    </el-radio>
                    <el-radio label="0" value="0">
                        锁定
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="性别" style="margin-left: 100px;" prop="ssex">
                <el-radio-group v-model="form.data.ssex">
                    <el-radio label="0" value="0">
                        男
                    </el-radio>
                    <el-radio label="1" value="1">
                        女
                    </el-radio>
                    <el-radio label="2" value="2">
                        保密
                    </el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="realAdd()">确认</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" title="删除确认" width="30%">
        <span>你确定要删除以下用户吗？
            <p style="margin-top: 10px;">{{state.delname.toString()}}</p>
        </span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="realDel()">确定</el-button>
            </span>
        </template>
    </el-dialog>

</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
// import FileSaver from "file-saver";
import * as XLSX from "xlsx";
import { ElMessage, ElTable, ElMessageBox } from 'element-plus'
import {
    Edit,
    View
} from '@element-plus/icons-vue'
import { getAllUserDataApi, addUserApi, changeUserApi, delUserApi } from '../../apis/user'
import { getDeptApi } from '../../apis/dept'
import { getAllRoleApi } from '../../apis/role'
import type { FormInstance } from 'element-plus'
const formInline = reactive({
    user: '',
    region: '',
    date: '',
})

interface User {
    [x: string]: string;
    date: string
    name: string
    address: string
}

const value1 = ref('')
const value2 = ref('1')
const dialogFormVisible = ref(false)
const dialogVisible = ref(false)
const formLabelWidth = '140px'

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const toggleSelection = (rows?: User[]) => {
    if (rows) {
        rows.forEach((row) => {
            // TODO: improvement typing when refactor table
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-expect-error
            multipleTableRef.value!.toggleRowSelection(row, undefined)
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }
}
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}

const state = reactive({
    userData: [] as any,
    page: 0,
    deptData: [] as any,
    roleData: [] as any,
    forChange: "新增",
    active: false,
    delname: [],
    delId: [],
    pageSize: 10,
    pageNum: 1

});

const form = reactive({
    data: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        role: "",
        dept: "",
        ssex: "",
        status: "",
        userId: ""
    }
})
const formbackup = reactive({
    dataBack: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        role: "",
        dept: "",
        ssex: "",
        status: "",
        userId: "",
    }
})
const handleEdit = (index: number, row: User) => {
    console.log(index, row)
    form.data = {
        username: row.username,
        password: row.password,
        email: row.email,
        mobile: row.mobile,
        role: row.roleId,
        dept: String(row.deptId),
        ssex: row.ssex,
        status: row.status,
        userId: row.userId
    }
    changeUser();
}
const handleDelete = (index: number, row: User) => {
    console.log(index, row)
}
const ruleFormRef = ref<FormInstance>()
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const filterTag = (value: string, row: User) => {
    return row.status === value
}
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    state.pageSize = val
    console.log(state.pageSize);
    getAll(`pageSize=${val}`)
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    state.pageNum = val
    getAll(`pageNum=${val}`)
}

const resetForm = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return;
    ruleForm.resetFields();
    getAll()
};

async function getAll(data?: any) {
    const res = await getAllUserDataApi(data)
    console.log(res);
    state.userData = res.rows
    state.page = res.total
}
async function getDept() {
    const res = await getDeptApi();
    console.log("dept", res);
    state.deptData = res.rows.children
}
async function getAllRole() {
    const res = await getAllRoleApi();
    console.log(res);
    state.roleData = res.rows

}
function onSubmit() {
    console.log(formInline.user);
    console.log(formInline.region);
    console.log(value1);

    getAll(`username=${formInline.user}&deptId=${formInline.region}&createTimeFrom=${formInline.date[0]}&createTimeTo=${formInline.date[1]}&`)

}
function addUser() {
    state.forChange = "新增用户"
    state.active = false
    dialogFormVisible.value = !dialogFormVisible.value
}
function changeUser() {
    state.forChange = "修改用户"
    state.active = true
    dialogFormVisible.value = !dialogFormVisible.value
}
function delect() {
    const data = JSON.parse(JSON.stringify(multipleSelection.value));
    console.log(data);
    const a = data.map((item: { userId: any }) => {
        return item.userId
    })
    state.delId = a
    const b = data.map((item: { username: any }) => {
        return item.username
    })
    state.delname = b
    state.delId = a
    console.log(a);
    console.log(b);
    if (data != "") {
        dialogVisible.value = true
    } else {
        ElMessage.error("没有选中任何用户，无法删除")
    }


}
//导出excel文件
function dataExcel() {
    // 设置当前日期
    let time = new Date();
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let day = time.getDate();
    let name = year + "" + month + "" + day;
    // console.log(name)
    /* generate workbook object from table */
    //  .table要导出的是哪一个表格
    var wb = XLSX.utils.table_to_book(document.querySelector(".table"));
    /* get binary string as output */
    var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
    });
    try {
        //  name+'.xlsx'表示导出的excel表格名字
        // FileSaver.saveAs(
        //     new Blob([wbout], { type: "application/octet-stream" }),
        //     name + ".xlsx"
        // );
    } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
    }
    return wbout;

}

function realDel() {
    delSome(state.delId)
    dialogVisible.value = false

}
async function realAdd() {
    dialogFormVisible.value = false
    const a = `username=${form.data.username}&password=${form.data.password}&email=${form.data.email}&mobile=${form.data.mobile}&roleId=${form.data.role}&deptId=${form.data.dept}&status=${form.data.status}&ssex=${form.data.ssex}`
    const b = `username=${form.data.username}&email=${form.data.email}&mobile=${form.data.mobile}&roleId=${form.data.role}&deptId=${form.data.dept}&status=${form.data.status}&ssex=${form.data.ssex}&userId=${form.data.userId}`
    if (state.active) {
        const res = await changeUserApi(b);
        console.log(res);
        if (res == "") {
            ElMessage.success("修改用户成功")
            console.log(state.pageSize);
            getAll(`pageSize=${state.pageSize}&pageNum=${state.pageNum}`);
        }
    }
    else {
        const res = await addUserApi(a);
        console.log(res);
        if (res == "") {
            ElMessage.success("新增用户成功");
            form.data = formbackup.dataBack;
            getAll(`pageSize=${state.pageSize}&pageNum=${state.pageNum}`);
        }
    }

}
async function delSome(data: any) {
    const res = await delUserApi(data)
    console.log(res);
    if (res == "") {
        ElMessage.success("删除用户成功")
        getAll(`pageSize=${state.pageSize}&pageNum=${state.pageNum}`);
    } else {
        ElMessage.error("删除失败")
    }
}
onMounted(() => {
    getAll();
    getDept();
    getAllRole();
})

</script>

<style scoped>
.demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
}

.demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    flex: 1;
}

.demo-date-picker .block:last-child {
    border-right: none;
}

.demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}

.demonstration {
    color: #616266;
    font-size: 14px;
}

.demo-pagination-block {
    margin-top: 20px;
}

.el-form--label-right {
    width: 80%;
}

.el-select {
    width: 100%;
}

.el-dropdown-link {
    margin-left: 10px;
}
.botton-group{
    margin-bottom: 10px;
}
</style>